using System;
using System.Data;
using System.Collections;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Business;
using mojoPortal.Business.Commerce;
using mojoPortal.Business.WebHelpers.PaymentGateway;
using eStore.Business;
using Resources;
using eStore.Helpers;
using GCheckout.Checkout;
using GCheckout.Util;

namespace eStore.UI
{

    public partial class ConfirmOrderPage : mojoBasePage
    {
        protected int pageId = -1;
        protected int moduleId = -1;
        protected Store store;
        protected GeoCountry storeCountry;
        protected Cart cart;
        protected SiteUser siteUser;
        protected DataTable tblCountryList;
        protected ArrayList checkoutErrors;
        private CommerceConfiguration commerceConfig;
        protected CultureInfo currencyCulture;
        private bool canCheckoutWithoutAuthentication;
        private eStoreConfiguration config = new eStoreConfiguration();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.SslIsAvailable()) SiteUtils.ForceSsl();

            //if (!UserCanViewPage(moduleId))
            //{
            //    SiteUtils.RedirectToAccessDeniedPage();
            //    return;
            //}

            // although we have implemented UI for separate customer, 
            // billing and shipping info, since first iteration supports
            // download only, just use customer
            // TODO: implement shippable products feature
            pnlBillingInfo.Visible = false;

            LoadSettings();

            if ((store == null) || (store.IsClosed))
            {
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                return;
            }

            SetupCss();
            PopulateLabels();
            PopulateControls();

        }

        private void PopulateControls()
        {
            if (!Page.IsPostBack)
            {
                BindBillingCountryList();
                BindCustomerCountryList();
                ShowCart();
            }

        }

        private void ShowCart()
        {
            if (cart == null) { return; }

            using (IDataReader reader = cart.GetItems())
            {
                rptCartItems.DataSource = reader;
                rptCartItems.DataBind();
            }

            litSubTotal.Text = StoreHelper.FormatPrice(cart.SubTotal.ToString(), currencyCulture);
            litDiscount.Text = StoreHelper.FormatPrice(cart.Discount.ToString(), currencyCulture);
            litTaxTotal.Text = StoreHelper.FormatPrice(cart.TaxTotal.ToString(), currencyCulture);
            litOrderTotal.Text = StoreHelper.FormatPrice(cart.OrderTotal.ToString(), currencyCulture);

            pnlDiscount.Visible = (cart.Discount > 0);
            pnlTaxTotal.Visible = (cart.TaxTotal > 0);

            if ((cart.ShippingTotal == 0) && (cart.TaxTotal == 0) && (cart.Discount == 0))
            {
                pnlSubTotal.Visible = false;
            }

            ListItem listItem;

            if (cart.OrderInfo == null)
            {
                listItem = ddBillingCountry.Items.FindByValue(storeCountry.IsoCode2);
                if (listItem != null)
                {
                    ddBillingCountry.ClearSelection();
                    listItem.Selected = true;
                }

                listItem = ddCustomerCountry.Items.FindByValue(storeCountry.IsoCode2);
                if (listItem != null)
                {
                    ddCustomerCountry.ClearSelection();
                    listItem.Selected = true;
                }

            }

            if (cart.OrderInfo != null && cart.OrderInfo.CustomerFirstName != string.Empty)
            {
                txtBillingFirstName.Text = cart.OrderInfo.BillingFirstName;
                txtBillingCompany.Text = cart.OrderInfo.BillingCompany;
                txtBillingAddress1.Text = cart.OrderInfo.BillingAddress1;
                txtBillingCity.Text = cart.OrderInfo.BillingCity;
                txtBillingPostalCode.Text = cart.OrderInfo.BillingPostalCode;

                listItem = ddBillingCountry.Items.FindByValue(cart.OrderInfo.BillingCountry.Trim());
                if (listItem != null)
                {
                    ddBillingCountry.ClearSelection();
                    listItem.Selected = true;
                }
                else
                {
                    if (storeCountry != null)
                    {
                        listItem = ddBillingCountry.Items.FindByValue(storeCountry.IsoCode2);
                        if (listItem != null)
                        {
                            ddBillingCountry.ClearSelection();
                            listItem.Selected = true;
                        }
                    }
                }

                txtCustomerName.Text = cart.OrderInfo.CustomerFirstName + cart.OrderInfo.CustomerLastName;
                txtCustomerCompany.Text = cart.OrderInfo.CustomerCompany;
                txtCustomerAddress.Text = cart.OrderInfo.CustomerAddressLine1;
                txtCustomerCity.Text = cart.OrderInfo.CustomerCity;
                txtCustomerPostalCode.Text = cart.OrderInfo.CustomerPostalCode;

                listItem = ddCustomerCountry.Items.FindByValue(cart.OrderInfo.CustomerCountry.Trim());
                if (listItem != null)
                {
                    ddCustomerCountry.ClearSelection();
                    listItem.Selected = true;
                }
                else
                {
                    if (storeCountry != null) listItem = ddCustomerCountry.Items.FindByValue(storeCountry.IsoCode2);
                    if (listItem != null)
                    {
                        ddCustomerCountry.ClearSelection();
                        listItem.Selected = true;
                    }
                }

                txtCustomerTelephoneDay.Text = cart.OrderInfo.CustomerTelephoneDay;
                txtCustomerEmail.Text = cart.OrderInfo.CustomerEmail;

                btnContinue.Enabled = store.IsValidForCheckout(cart, out checkoutErrors);

            }

            Page.Validate("OrderInfo");

            btnContinue.Enabled
                = (
                (Page.IsValid)
                && (store.IsValidForCheckout(cart, out checkoutErrors))
                );

        }

        private void BindBillingCountryList()
        {
            if (tblCountryList == null) return;
            ddBillingCountry.DataSource = tblCountryList;
            ddBillingCountry.DataBind();
            if (ddBillingCountry.Items.FindByValue("VN") != null)
            {
                ddBillingCountry.Items.FindByValue("VN").Selected = true;
            }
        }

        private void BindCustomerCountryList()
        {
            if (tblCountryList == null) return;
            ddCustomerCountry.DataSource = tblCountryList;
            ddCustomerCountry.DataBind();
            if (ddCustomerCountry.Items.FindByValue("VN") != null)
            {
                ddCustomerCountry.Items.FindByValue("VN").Selected = true;
            }
        }

        private void SaveCartDetail()
        {
            if (cart == null) { return; }

            GeoCountry country;
            GeoZone taxZone;

            cart.OrderInfo.CustomerFirstName = txtCustomerName.Text;
            cart.OrderInfo.CustomerCompany = txtCustomerCompany.Text;
            cart.OrderInfo.CustomerAddressLine1 = txtCustomerAddress.Text;
            cart.OrderInfo.CustomerCity = txtCustomerCity.Text;
            cart.OrderInfo.CustomerPostalCode = txtCustomerPostalCode.Text;
            cart.OrderInfo.CustomerState = string.Empty;
            cart.OrderInfo.CustomerCountry = ddCustomerCountry.SelectedItem.Value;
            cart.OrderInfo.CustomerTelephoneDay = txtCustomerTelephoneDay.Text;
            cart.OrderInfo.CustomerEmail = txtCustomerEmail.Text;

            if (cart.OrderInfo.CustomerState.Length > 0)
            {
                country = new GeoCountry(cart.OrderInfo.CustomerCountry);
                taxZone = GeoZone.GetByCode(country.Guid, cart.OrderInfo.CustomerState);

                cart.OrderInfo.TaxZoneGuid = taxZone.Guid;
            }

                cart.OrderInfo.DeliveryFirstName = txtCustomerName.Text;
                cart.OrderInfo.DeliveryCompany = txtCustomerCompany.Text;
                cart.OrderInfo.DeliveryAddress1 = txtCustomerAddress.Text;
                cart.OrderInfo.DeliveryCity = txtCustomerCity.Text;
                cart.OrderInfo.DeliveryPostalCode = txtCustomerPostalCode.Text;
                cart.OrderInfo.DeliveryState = string.Empty;
                cart.OrderInfo.DeliveryCountry = ddCustomerCountry.SelectedItem.Value;

            if (pnlBillingInfo.Visible)
            {
                cart.OrderInfo.BillingFirstName = txtBillingFirstName.Text;
                cart.OrderInfo.BillingCompany = txtBillingCompany.Text;
                cart.OrderInfo.BillingAddress1 = txtBillingAddress1.Text;
                cart.OrderInfo.BillingCity = txtBillingCity.Text;
                cart.OrderInfo.BillingPostalCode = txtBillingPostalCode.Text;
                cart.OrderInfo.BillingState = string.Empty;
                cart.OrderInfo.BillingCountry = ddBillingCountry.SelectedItem.Value;
            }
            else
            {
                cart.OrderInfo.BillingFirstName = txtCustomerName.Text;
                cart.OrderInfo.BillingCompany = txtCustomerCompany.Text;
                cart.OrderInfo.BillingAddress1 = txtCustomerAddress.Text;
                cart.OrderInfo.BillingCity = txtCustomerCity.Text;
                cart.OrderInfo.BillingPostalCode = txtCustomerPostalCode.Text;
                cart.OrderInfo.BillingState = string.Empty;
                cart.OrderInfo.BillingCountry = ddCustomerCountry.SelectedItem.Value;
            }

            cart.OrderInfo.CompletedFromIP = SiteUtils.GetIP4Address();
            cart.OrderInfo.Save();
            cart.RefreshTotals();


        }

        private void btnSaveAndValidate_Click(object sender, EventArgs e)
        {
            Page.Validate("OrderInfo");
            if (Page.IsValid)
            {
                SaveCartDetail();

                WebUtils.SetupRedirect(this, Request.RawUrl);
            }
            else
            {
                btnContinue.Enabled = false;

            }
        }

        private void lnkCopyCustomerToBilling_Click(object sender, EventArgs e)
        {
            if (cart == null) { return; }

            SaveCartDetail();
            cart.CopyShippingToBilling();
            cart.RefreshTotals();

            WebUtils.SetupRedirect(this, Request.RawUrl);
            return;

        }

        private void btnContinue_Click(object sender, EventArgs e)
        {
            SaveCartDetail();

            string checkoutUrl = SiteRoot + "/eStore/Checkout.aspx?pageid="
                + pageId.ToString(CultureInfo.InvariantCulture)
                + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);


            if (store.IsValidForCheckout(cart, out checkoutErrors))
            {
                WebUtils.SetupRedirect(this, checkoutUrl);
                return;
            }
            ShowCheckoutErrors();
        }

        private void ShowCheckoutErrors()
        {
            if (checkoutErrors != null)
            {



            }


        }

        void btnPayPal_Click(object sender, ImageClickEventArgs e)
        {
            if (commerceConfig.PayPalUsePayPalStandard)
            {
                DoPayPalStandardCheckout();
            }
            else
            {
                DoPayPalExpressCeckout();
            }
        }


        private void DoPayPalExpressCeckout()
        {
            PayPalExpressGateway gateway
                = new PayPalExpressGateway(
                    commerceConfig.PayPalAPIUsername,
                    commerceConfig.PayPalAPIPassword,
                    commerceConfig.PayPalAPISignature,
                    commerceConfig.PayPalStandardEmailAddress)
                      {
                          UseTestMode = commerceConfig.PaymentGatewayUseTestMode,
                          MerchantCartId = cart.CartGuid.ToString(),
                          ChargeTotal = cart.OrderTotal
                      };

            string siteRoot = SiteUtils.GetNavigationSiteRoot();
            gateway.ReturnUrl = siteRoot + "/Services/PayPalReturnHandler.ashx";
            gateway.CancelUrl = siteRoot + Request.RawUrl;
            //Currency currency = new Currency(store.DefaultCurrencyId);
            //gateway.CurrencyCode = currency.Code;
            gateway.CurrencyCode = siteSettings.GetCurrency().Code;
            gateway.OrderDescription = store.Name + " " + eStoreResources.OrderHeading;

            gateway.BuyerEmail = cart.OrderInfo.CustomerEmail;
            gateway.ShipToFirstName = cart.OrderInfo.DeliveryFirstName;
            gateway.ShipToLastName = cart.OrderInfo.DeliveryLastName;
            gateway.ShipToAddress = cart.OrderInfo.DeliveryAddress1;
            gateway.ShipToAddress2 = cart.OrderInfo.DeliveryAddress2;
            gateway.ShipToCity = cart.OrderInfo.DeliveryCity;
            gateway.ShipToState = cart.OrderInfo.DeliveryState;
            gateway.ShipToCountry = cart.OrderInfo.DeliveryCountry;
            gateway.ShipToPostalCode = cart.OrderInfo.DeliveryPostalCode;
            gateway.ShipToPhone = cart.OrderInfo.CustomerTelephoneDay;

            // this tells paypal to use the shipping address we pass in
            // rather than what the customer has on file
            // when we implement shippable products we'll do shipping calculations before
            // sending the user to paypal
            //gateway.OverrideShippingAddress = true;

            //commented out the above, we want user to be able to populate shipping info from their paypal account

            bool executed = gateway.CallSetExpressCheckout();
            if (executed)
            {
                //TODO: log the raw response
                if (gateway.PayPalExpressUrl.Length > 0)
                {
                    // record the gateway.PayPalToken
                    PayPalLog payPalLog = new PayPalLog
                                              {
                                                  RawResponse = gateway.RawResponse,
                                                  ProviderName = eStorePayPalReturnHandler.ProviderName,
                                                  ReturnUrl = siteRoot + Request.RawUrl,
                                                  Token = HttpUtility.UrlDecode(gateway.PayPalToken),
                                                  RequestType = "SetExpressCheckout"
                                              };
                    //payPalLog.PendingReason = gateway.PayPalExpressUrl;

                    cart.SerializeCartProducts();
                    payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart);

                    payPalLog.CartGuid = cart.CartGuid;
                    payPalLog.SiteGuid = store.SiteGuid;
                    payPalLog.StoreGuid = store.Guid;
                    payPalLog.UserGuid = cart.UserGuid;

                    payPalLog.Save();

                    Response.Redirect(gateway.PayPalExpressUrl);

                }

            }

        }

        /// <summary>
        /// This is really a fallback method, it will not be executed in normal use because we are setting the postbackurl of the button
        /// to post directly to paypal, so this method should not fire unless somehow the page is manipulated to postback to itself.
        /// In this case, we just consolidate the cart into a buy now button.
        /// </summary>
        private void DoPayPalStandardCheckout()
        {
            PayPalLog payPalLog = new PayPalLog
                                      {
                                          ProviderName = eStorePayPalReturnHandler.ProviderName,
                                          PDTProviderName = eStorePayPalPDTHandlerProvider.ProviderName,
                                          IPNProviderName = eStorePayPalIPNHandlerProvider.ProviderName,
                                          ReturnUrl = SiteRoot +
                                                      "/eStore/OrderDetail.aspx?pageid="
                                                      + pageId.ToString(CultureInfo.InvariantCulture)
                                                      + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
                                                      + "&orderid=" + cart.CartGuid,
                                          RequestType = "StandardCheckout"
                                      };

            cart.SerializeCartProducts();
            payPalLog.SerializedObject = SerializationHelper.SerializeToString(cart);

            //Currency currency = new Currency(store.DefaultCurrencyId);

            payPalLog.CartGuid = cart.CartGuid;
            payPalLog.SiteGuid = store.SiteGuid;
            payPalLog.StoreGuid = store.Guid;
            payPalLog.UserGuid = cart.UserGuid;
            payPalLog.CartTotal = cart.OrderTotal;
            payPalLog.CurrencyCode = siteSettings.GetCurrency().Code;

            payPalLog.Save();

            string payPalStandardUrl = StoreHelper.GetBuyNowUrl(
                payPalLog.RowGuid,
                cart,
                store,
                commerceConfig);


            WebUtils.SetupRedirect(this, payPalStandardUrl);

        }

        private void SetupPayPalStandardForm()
        {
            if (cart == null) { return; }
            if (siteUser == null) { return; }

            if (cart.UserGuid == Guid.Empty)
            {
                cart.UserGuid = siteUser.UserGuid;
                cart.Save();
            }

            if (cart.CartProducts.Count == 0)
            {
                litOr.Visible = false;
                btnPayPal.Visible = false;
                btnGoogleCheckout.Visible = false;
                return;
            }

            PayPalLog payPalLog = StoreHelper.EnsurePayPalStandardCheckoutLog(cart, store, SiteRoot, pageId, moduleId);
            if (payPalLog == null) return;

            litPayPalFormVariables.Text = StoreHelper.GetCartUploadFormFields(
                payPalLog.RowGuid,
                cart,
                store,
                commerceConfig);

            btnPayPal.PostBackUrl = commerceConfig.PayPalStandardUrl;
        }

        void btnGoogleCheckout_Click(object sender, ImageClickEventArgs e)
        {
            if (
                (store != null)
                && (cart != null)
                )
            { //&& (IsValidForCheckout()) ?

                const int cartTimeoutInMinutes = 30;
                //string currency = "USD";
                //CheckoutShoppingCartRequest Req = btnGoogleCheckout.CreateRequest();
                CheckoutShoppingCartRequest Req = new CheckoutShoppingCartRequest(
                    commerceConfig.GoogleMerchantID,
                    commerceConfig.GoogleMerchantKey,
                    commerceConfig.GoogleEnvironment,
                    siteSettings.GetCurrency().Code,
                    cartTimeoutInMinutes);


                foreach (CartProduct cartProduct in cart.CartProducts)
                {

                    Req.AddItem(
                        cartProduct.Name,
                        string.Empty,
                        cartProduct.ProductPrice,
                        cartProduct.Quantity);
                }

                //Req.AddMerchantCalculatedShippingMethod
                //Req.AnalyticsData
                //Req.ContinueShoppingUrl
                //Req.EditCartUrl

                //Req.RequestInitialAuthDetails
                //Req.AddParameterizedUrl

                // we need to serialize the cart and it items to xml here
                // so when we get it back from google
                // we can validate against the existing cart
                // as its possible items were added to the cart
                // after we passed the user to google

                //Req.MerchantPrivateData = cart.CartGuid.ToString();
                //cart.SerializeCartProducts();
                //Req.MerchantPrivateData = SerializationHelper.SerializeToSoap(cart);

                cart.SerializeCartProducts();
                MerchantData merchantData = new MerchantData
                                                {
                                                    ProviderName = "eStoreGCheckoutNotificationHandlerProvider",
                                                    SerializedObject =
                                                        SerializationHelper.RemoveXmlDeclaration(
                                                            SerializationHelper.SerializeToString(cart))
                                                };

                Req.MerchantPrivateData = SerializationHelper.RemoveXmlDeclaration(SerializationHelper.SerializeToString(merchantData));

                Req.RequestBuyerPhoneNumber = true;




                // flat rate shipping example
                //Req.AddFlatRateShippingMethod("UPS Ground", 5);

                //Add a rule to tax all items at 7.5% for Ohio
                //Req.AddStateTaxRule("NC", .15, true);
                //TODO: lookup tax 

                GCheckoutResponse Resp = Req.Send();


                if (Resp.IsGood)
                {
                    Response.Redirect(Resp.RedirectUrl, true);
                }
                else
                {
                    lblMessage.Text = Resp.ErrorMessage;
                }
            }

        }


        private void PopulateLabels()
        {
            
            moduleTitle.Header = eStoreResources.ConfirmOrderHeading;
            Title = SiteUtils.FormatPageTitle(siteSettings, CurrentPage.PageName + " - " + eStoreResources.ConfirmOrderHeading);
            litCartHeader.Text = eStoreResources.ProductList;

            SignInOrRegisterPrompt signinPrompt = srPrompt;
            signinPrompt.Instructions = canCheckoutWithoutAuthentication ? eStoreResources.CheckoutSuggestLoginOrRegisterMessage : eStoreResources.CheckoutRequiresLoginOrRegisterMessage;

            litOr.Text = eStoreResources.LiteralOr;
            lnkCopyCustomerToBilling.Text = eStoreResources.CopyCustomerToBillingLink;
            lnkCopyCustomerToBilling.ToolTip = eStoreResources.CopyCustomerToBillingLink;

            lnkCart.Visible = config.ShowCartLinkSetting;

            reqBillingAddress1.Text = eStoreResources.RequiredFieldSymbol;
            reqBillingAddress1.ErrorMessage = eStoreResources.BillingAddress1RequiredMessage;
            reqBillingCity.Text = eStoreResources.RequiredFieldSymbol;
            reqBillingCity.ErrorMessage = eStoreResources.BillingCityRequiredMessage;
            reqBillingFirstName.Text = eStoreResources.RequiredFieldSymbol;
            reqBillingFirstName.ErrorMessage = eStoreResources.BillingFirstNameRequiredMessage;
            reqBillingPostalCode.Text = eStoreResources.RequiredFieldSymbol;
            reqBillingPostalCode.ErrorMessage = eStoreResources.BillingPostalCodeRequiredMessage;

            reqCustomerDayPhone.Text = eStoreResources.RequiredFieldSymbol;
            reqCustomerDayPhone.ErrorMessage = eStoreResources.CustomerDayPhoneRequiredMessage;
            reqCustomerEmail.Text = eStoreResources.RequiredFieldSymbol;
            reqCustomerEmail.ErrorMessage = eStoreResources.CustomerEmailRequiredMessage;

            regexCustomerEmail.Text = eStoreResources.RequiredFieldSymbol;
            regexCustomerEmail.ErrorMessage = eStoreResources.CustomerEmailRegexFailureMessage;
            regexCustomerEmail.ValidationExpression = SecurityHelper.RegexEmailValidationPattern;

            btnSaveAndValidate.Text = eStoreResources.UpdateCustomerButton;
            btnContinue.Text = eStoreResources.ContinueButton;
            btnGoogleCheckout.UseHttps = SiteUtils.SslIsAvailable();

            lnkCart.PageID = pageId;
            lnkCart.ModuleID = moduleId;


        }



        private void ConfigureCheckoutButtons()
        {
            bool shouldShowPayPal = ShouldShowPayPal();
            bool shouldShowGoogle = ShouldShowGoogle();

            btnPayPal.Visible = shouldShowPayPal;
            btnGoogleCheckout.Visible = shouldShowGoogle;
            litOr.Visible = (shouldShowPayPal || shouldShowGoogle);

            if (shouldShowGoogle)
            {
                if ((!commerceConfig.Is503TaxExempt) && (cart.HasDonations()))
                {
                    lblGoogleMessage.Text = eStoreResources.GoogleCheckoutDisabledForDonationsMessage;
                    lblGoogleMessage.Visible = true;
                    btnGoogleCheckout.Enabled = false;
                    if (!Request.IsAuthenticated)
                    {
                        PaymentAcceptanceMark mark = pam1;
                        mark.SuppressGoogleCheckout = true;
                    }
                }

            }

            if ((shouldShowPayPal) && (commerceConfig.PayPalUsePayPalStandard))
            {
                SetupPayPalStandardForm();
            }


        }

        private void LoadSettings()
        {
            commerceConfig = SiteUtils.GetCommerceConfig();
            storeCountry = new GeoCountry(siteSettings.DefaultCountryGuid);

            pnlStoreManager.CssClass += " " + config.CustomCssClassSetting + "-cart";

            if (Request.IsAuthenticated)
            {
                siteUser = SiteUtils.GetCurrentSiteUser();
            }

            if (CurrentPage.ContainsModule(moduleId))
            {
                store = StoreHelper.GetStore();
            }

            if (
                (store != null)
                && (StoreHelper.UserHasCartCookie(store.Guid))
                )
            {
                cart = StoreHelper.GetCart();

                if (cart != null)
                {
                    if ((cart.LastModified < DateTime.UtcNow.AddDays(-1)) && (cart.DiscountCodesCsv.Length > 0))
                    {
                        StoreHelper.EnsureValidDiscounts(store, cart);
                    }

                    if (siteUser != null)
                    {
                        if (cart.UserGuid == Guid.Empty)
                        {
                            // take ownership of anonymous cart
                            cart.UserGuid = siteUser.UserGuid;
                            cart.Save();
                            StoreHelper.InitializeOrderInfo(cart, siteUser);
                        }
                        else
                        {
                            // cart already has a user guid but 
                            // check if it matches the current user
                            // cart cookie could have been left behind by a previous user
                            // on shared computers
                            // if cart user guid doesn't match reset billing shipping info
                            // and any other identifiers
                            // but leave items in cart
                            if (cart.UserGuid != siteUser.UserGuid)
                            {
                                cart.ResetUserInfo();
                                cart.UserGuid = siteUser.UserGuid;
                                cart.Save();
                                StoreHelper.InitializeOrderInfo(cart, siteUser);
                            }
                        }
                    }

                    if (store != null)
                    {
                        canCheckoutWithoutAuthentication = store.CanCheckoutWithoutAuthentication(cart);
                    }

                    // disable till I finish
                    //canCheckoutWithoutAuthentication = false;

                }

            }


            pnlRequireLogin.Visible = !Request.IsAuthenticated;

            if ((canCheckoutWithoutAuthentication) || (Request.IsAuthenticated))
            {
                pnlOrderDetail.Visible = commerceConfig.CanProcessStandardCards || config.UseEmailSystemOnlySetting;
                pnlRequireLogin.Visible = config.RequireLoginToOrder;
                pnlTaxTotal.Visible = false;
                //pnlOrderTotal.Visible = true;

            }

            if (pnlOrderDetail.Visible) { tblCountryList = GeoCountry.GetList(); }


            ConfigureCheckoutButtons();

            //if (!Page.IsPostBack)
            //{
            //    if ((commerceConfig.PayPalIsEnabled) && (commerceConfig.PayPalUsePayPalStandard))
            //    {
            //        if (Request.IsAuthenticated)
            //        {
            //            SetupPayPalStandardForm();
            //        }
            //        else
            //        {
            //            // we need the user to be signed in before we send them to paypal if using PayPal Standard
            //            // because we want to return them to their order summary and that requires login
            //            // so we need to know who the user is before sending them to PayPal
            //            litOr.Visible = false;
            //            btnPayPal.Visible = false;
            //            btnGoogleCheckout.Visible = false;
            //        }
            //    }
            //}

            //if (!Request.IsAuthenticated)
            //{

            //    pnlOrderDetail.Visible = false;
            //    pnlRequireLogin.Visible = true;
            //    pnlShippingTotal.Visible = false;
            //    pnlTaxTotal.Visible = false;
            //    pnlOrderTotal.Visible = false;

            //    if (commerceConfig.GoogleCheckoutIsEnabled)
            //    {
            //        if (
            //        (!commerceConfig.Is503TaxExempt)
            //        && ((cart != null) && (cart.HasDonations()))
            //        )
            //        {
            //            //btnGoogleCheckout.Visible = false;
            //            lblGoogleMessage.Text = eStoreResources.GoogleCheckoutDisabledForDonationsMessage;
            //            lblGoogleMessage.Visible = true;
            //            PaymentAcceptanceMark mark = (PaymentAcceptanceMark)pam1;
            //            mark.SuppressGoogleCheckout = true;

            //            mark = (PaymentAcceptanceMark)PaymentAcceptanceMark1;
            //            mark.SuppressGoogleCheckout = true;

            //            btnGoogleCheckout.Visible = true;
            //            btnGoogleCheckout.Enabled = false;
            //        }
            //    }

            //}
            //else
            //{
            //    if (
            //        (!commerceConfig.Is503TaxExempt)
            //         && ((cart != null)&& (cart.HasDonations()))
            //        && (commerceConfig.GoogleCheckoutIsEnabled)
            //        )
            //    {
            //        btnGoogleCheckout.Visible = true;
            //        btnGoogleCheckout.Enabled = false;
            //        lblGoogleMessage.Text = eStoreResources.GoogleCheckoutDisabledForDonationsMessage;
            //        lblGoogleMessage.Visible = true;
            //    }


            //}

        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);

        }

        private bool ShouldShowPayPal()
        {
            if (store == null) { return false; }
            if (cart == null) { return false; }
            if (cart.SubTotal == 0) { return false; }
            if (cart.OrderTotal == 0) { return false; }
            if (commerceConfig == null) { return false; }
            if ((!Request.IsAuthenticated) && (!canCheckoutWithoutAuthentication)) { return false; }
            if (!commerceConfig.PayPalIsEnabled) { return false; }



            return true;
        }

        private bool ShouldShowGoogle()
        {
            if (store == null) { return false; }
            if (cart == null) { return false; }
            if (cart.SubTotal == 0) { return false; }
            if (cart.OrderTotal == 0) { return false; }
            if (commerceConfig == null) { return false; }
            if ((!Request.IsAuthenticated) && (!canCheckoutWithoutAuthentication)) { return false; }
            if (!commerceConfig.GoogleCheckoutIsEnabled) { return false; }

            return true;
        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
                                  {
                                      ID = "styleestore",
                                      Text = @"<link href='"
                                             + SiteUtils.GetSkinBaseUrl()
                                             + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
                                  };

            stylesheet.Controls.Add(cssLink);
        }


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            Load += Page_Load;
            btnSaveAndValidate.Click += btnSaveAndValidate_Click;
            btnContinue.Click += btnContinue_Click;
            lnkCopyCustomerToBilling.Click += lnkCopyCustomerToBilling_Click;
            btnPayPal.Click += btnPayPal_Click;
            btnGoogleCheckout.Click += btnGoogleCheckout_Click;

            SuppressPageMenu();
            SuppressGoogleAds();

        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new eStoreConfiguration(settings);
            LoadSideContent(config.ShowLeftPanelSetting, config.ShowRightPanelSetting, config.ShowTopPanelSetting, config.ShowBottomPanelSetting, config.ShowCenterPanelSetting);
        }
        #endregion

    }
}
